package com.example.partner.adapter.find;// MyPostsAdapter.java

import static android.content.ContentValues.TAG;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.partner.R;
import com.example.partner.activity.find.EditPostActivity;
import com.example.partner.activity.find.PostDetailActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.Post;
import com.example.partner.service.PostService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyPostsAdapter extends RecyclerView.Adapter<MyPostsAdapter.MyPostViewHolder> {

    private List<Post> postList;
    private Context context;
    private View view;

    public MyPostsAdapter(List<Post> postList, Context context) {
        this.postList = postList;
        this.context = context;
    }

    @NonNull
    @Override
    public MyPostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_my_post, parent, false);
        return new MyPostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyPostViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.textViewTitle.setText(post.getTitle());
        holder.textViewCreateTime.setText(post.getCreateTime().toString());
        holder.textViewLikeCount.setText(String.valueOf(post.getLiked()));
        holder.textViewCommentCount.setText(String.valueOf(post.getComments()));
        // 设置帖子的第一张图片，这里假设有多张图片用逗号分隔
        String[] images = post.getAvatarUrl() != null ? post.getAvatarUrl().split(",") : new String[0];
        // 如果有图片就加载第一张
        if (images.length > 0) {
            // 使用你的图片加载库加载图片，这里用占位符代替
            Glide.with(context).load(images[0]).placeholder(R.drawable.placeholder_image).into(holder.imageViewPost);
        }
        long postId = post.getId();
        // 设置帖子项的点击事件，跳转到帖子详情页
        holder.imageViewPost.setOnClickListener(v -> {
            // 获取当前帖子的ID（假设你的帖子类中有一个getId()方法）
            // 创建 Intent，并传递帖子的ID到 PostDetailActivity
            Intent intent = new Intent(view.getContext(), PostDetailActivity.class);
            intent.putExtra("postId", postId);
            // 启动帖子详情页
            view.getContext().startActivity(intent);
        });
        // Set click listener for the item view
        holder.buttonEdit.setOnClickListener(v -> {
            // Handle edit button click
            Intent intent = new Intent(view.getContext(), EditPostActivity.class);
            intent.putExtra("postId", postId);
            view.getContext().startActivity(intent);
        });
        holder.buttonDelete.setOnClickListener(v -> showDeleteConfirmationDialog(post.getId()));
    }
    private void showDeleteConfirmationDialog(long postId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("确认删除");
        builder.setMessage("是否确认删除该帖子？");
        builder.setPositiveButton("确认", (dialog, which) -> {
            // 调用删除接口
            deletePost(postId);
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
            // 用户取消删除操作
            dialog.dismiss();
        });
        builder.create().show();
    }

    private void deletePost(long postId) {
        // 调用删除接口，可以使用 Retrofit 或其他方式发送删除请求
        // ...
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        Call<Boolean> call = postService.deletePost(postId);
        call.enqueue(new Callback<Boolean>() {
            @Override
            public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                if (response.isSuccessful()) {
                    if (response.body().booleanValue()){
                        Toast.makeText(view.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(view.getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }

            @Override
            public void onFailure(Call<Boolean> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });

        // 更新 UI，例如从列表中移除被删除的帖子
        int position = findPostPositionById(postId);
        if (position != -1) {
            postList.remove(position);
            notifyItemRemoved(position);
        }
    }

    private int findPostPositionById(long postId) {
        for (int i = 0; i < postList.size(); i++) {
            if (postList.get(i).getId() == postId) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int getItemCount() {
        if (postList==null){
            return 0;
        }
        return postList.size();
    }



    public static class MyPostViewHolder extends RecyclerView.ViewHolder {
        TextView textViewTitle,textViewLikeCount,textViewCommentCount;
        TextView textViewCreateTime;
        // Add other views as needed
        Button buttonEdit;
        Button buttonDelete;
        ImageView imageViewPost, imageViewLike, imageViewComment;

        public MyPostViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewCreateTime = itemView.findViewById(R.id.textViewTime);
            // Initialize other views
            buttonEdit = itemView.findViewById(R.id.buttonEdit);
            buttonDelete = itemView.findViewById(R.id.buttonDelete);
            imageViewPost = itemView.findViewById(R.id.imageViewPost);
            imageViewLike = itemView.findViewById(R.id.imageViewLike);
            imageViewComment = itemView.findViewById(R.id.imageViewComment);
            textViewLikeCount = itemView.findViewById(R.id.textViewLikeCount);
            textViewCommentCount = itemView.findViewById(R.id.textViewCommentCount);

        }
    }
}
